package controllers

import (
	"github.com/kataras/iris"
	"lottery/comm"
	"lottery/models"
	"lottery/services"
	"lottery/web/utils"
)

type ResultController struct {
	Ctx           iris.Context
	ServiceUser   services.UserService
	ServiceEvent  services.EventService
	ServiceAward  services.AwardService
	ServiceResult services.ResultService
}

// POST /result/my params: token
// 我的中奖的活动列表
func (c *ResultController) PostMy() map[string]interface{} {
	token := c.Ctx.FormValue("token")
	ret, claims, err := utils.VerifyESToken(token)
	if err != nil {
		// token 解析失败
		return utils.RespCode(500)
	} else if !ret {
		// token 无效
		return utils.RespCode(100)
	}

	userId := int(comm.GetInt64(claims.Get("user_id"), -1))

	results := c.ServiceResult.GetByWinner(userId)

	respEvents := make([]models.ResultRespEvent, 0)
	respAwards := make([]models.ResultRespAwards, 0)

	for _, result := range results {
		has, data := c.ServiceEvent.Get(result.EventId)
		if !has {
			return utils.RespCode(500)
		}
		award := c.ServiceAward.Get(result.AwardId)
		awards := c.ServiceAward.GetByEvent(result.EventId)
		for _, award := range awards {
			respAwards = append(respAwards, models.ResultRespAwards{
				ID:        award.Id,
				Name:      award.Name,
				Desc:      award.Desc,
				MaxAmount: award.MaxAmount,
				Img:       award.Img,
			})
		}
		respEvents = append(respEvents, models.ResultRespEvent{
			ID:     data.Id,
			Name:   data.Name,
			Desc:   data.Desc,
			Type:   data.Type,
			Img:    data.Img,
			Status: data.Status,
			Awards: respAwards,
			Result: models.ResultRespResult{
				AwardName: award.Name,
				AwardImg:  award.Img,
				AwardCode: result.AwardCode,
			},
		})
		respAwards = make([]models.ResultRespAwards, 0)
	}
	return map[string]interface{}{
		"code": 0,
		"msg":  "success",
		"data": respEvents,
	}
}
